package com.handpay.nocardpay.baselibrary.qualificationinfo.view.fragment;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.handpay.nocardpay.baselibrary.R;
import com.handpay.nocardpay.baselibrary.commbase.BaseProtocolKey;
import com.handpay.nocardpay.baselibrary.commbase.view.fragment.BaseFragment;
import com.handpay.nocardpay.baselibrary.config.SecureManager;
import com.handpay.nocardpay.baselibrary.logutils.HPLog;
import com.handpay.nocardpay.baselibrary.permission.PermissionCode;
import com.handpay.nocardpay.baselibrary.permission.PermissionRequest;
import com.handpay.nocardpay.baselibrary.qualificationinfo.comm.CommonHelper;
import com.handpay.nocardpay.baselibrary.qualificationinfo.model.bean.IDCardStatus;
import com.handpay.nocardpay.baselibrary.qualificationinfo.presenter.QualificationPresenterImpl;
import com.handpay.nocardpay.baselibrary.qualificationinfo.view.IIDCardSupplementView;
import com.handpay.nocardpay.baselibrary.qualificationinfo.widgets.QualificationPhotoView;
import com.handpay.nocardpay.baselibrary.utils.AccountUtils;
import com.handpay.nocardpay.baselibrary.utils.ClientEngine;
import com.handpay.nocardpay.baselibrary.utils.CommonUtils;
import com.handpay.nocardpay.baselibrary.utils.DialogUtils;
import com.handpay.nocardpay.baselibrary.utils.MyAsyncTask;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;

import java.util.HashMap;
import java.util.List;

/**
 * Created by fplei on 2017/8/18.
 * 证件补齐
 */

public class IDCardSupplementFragment extends BaseFragment implements IIDCardSupplementView,PermissionRequest.onPermissionRequestCallBack {
    public static int TAKE_PICTURE = 1;
    public static int TAKE_PICTURE_FRONT = TAKE_PICTURE + 1;
    public static int TAKE_PICTURE_BLACK = TAKE_PICTURE + 2;
    public static int TAKE_PICTURE_IN_HAND = TAKE_PICTURE + 3;
    private Toolbar mToolbar;
    private LinearLayout reupload_warning, linear_tip_detail, linear_card;
    private ImageView img_uploadcard_stuts;
    private TextView tv_failDes, tv_tip_of_card, tv_tip_of_card_name, tv_tip_of_card_number, tv_failDes0;
    private QualificationPhotoView c_id_front_photo, c_id_back_photo, c_person_with_id;
    private Button btn_upload_cardpic;
    private IDCardStatus cardStatus=new IDCardStatus();
    private QualificationPresenterImpl qualificationPresenterImpl;
    private Uri mPicUri;
    private MyAsyncTask<Void, BaseProtocolKey.TYPE, Integer> mTask;
    private ProgressDialog progressDialog = null;
    private volatile boolean mFrontUploaded = false;
    private volatile boolean mBackUploaded = false;
    private volatile boolean mInHandUploaded = false;
    private ScrollView root_scroll;
    private PermissionRequest permissonRequest;
    private int CurrentRequestCode=0;
    private String[] permissons= Permission.CAMERA;

    public static IDCardSupplementFragment newInstance() {
        Bundle args = new Bundle();
        IDCardSupplementFragment fragment = new IDCardSupplementFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_idcardsupplement;
    }

    @Override
    public String getFragmentTitle() {
        return getString(R.string.card_reupload_title);
    }

    private QualificationPhotoView.UploadClickListener mUploadClickListener = new QualificationPhotoView.UploadClickListener() {
        @Override
        public void onUploadClickListener(QualificationPhotoView view) {
            CurrentRequestCode = TAKE_PICTURE;
            if (c_id_front_photo == view) {
                CurrentRequestCode = TAKE_PICTURE_FRONT;
            } else if (c_id_back_photo == view) {
                CurrentRequestCode = TAKE_PICTURE_BLACK;
            } else if (c_person_with_id == view) {
                CurrentRequestCode = TAKE_PICTURE_IN_HAND;
            }
            permissonRequest.requestPermission(permissons);
        }
        @Override
        public void checkBigPitcure(String uri) {
            String temp_uri = uri;
            start(BigPictureFragment.newInstance(temp_uri));
        }
    };

    @Override
    public void initView(View view) {
        mToolbar = (Toolbar) view.findViewById(R.id.toolbar);
        initToolbar(mToolbar, true);
        root_scroll=(ScrollView)view.findViewById(R.id.root_scroll);
        root_scroll.setVisibility(View.INVISIBLE);
        reupload_warning = (LinearLayout) view.findViewById(R.id.reupload_warning);
        img_uploadcard_stuts = (ImageView) view.findViewById(R.id.img_uploadcard_stuts);
        tv_failDes = (TextView) view.findViewById(R.id.tv_failDes);
        linear_tip_detail = (LinearLayout) view.findViewById(R.id.linear_tip_detail);
        tv_tip_of_card = (TextView) view.findViewById(R.id.tv_tip_of_card);
        tv_tip_of_card_name = (TextView) view.findViewById(R.id.tv_tip_of_card_name);
        tv_tip_of_card_number = (TextView) view.findViewById(R.id.tv_tip_of_card_number);
        linear_card = (LinearLayout) view.findViewById(R.id.linear_card);
        c_id_front_photo = (QualificationPhotoView) view.findViewById(R.id.c_id_front_photo);
        c_id_back_photo = (QualificationPhotoView) view.findViewById(R.id.c_id_back_photo);
        c_person_with_id = (QualificationPhotoView) view.findViewById(R.id.c_person_with_id);
        btn_upload_cardpic = (Button) view.findViewById(R.id.btn_upload_cardpic);
        tv_failDes0 = (TextView) view.findViewById(R.id.tv_failDes0);
        refreshView();
    }

    @Override
    public void initListener() {
        btn_upload_cardpic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                submitIDCardInfo();
            }
        });
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        permissonRequest=new PermissionRequest(_mActivity,this);
        qualificationPresenterImpl = new QualificationPresenterImpl(_mActivity, this);
        queryUserIDCardInfo();
    }

    private void queryUserIDCardInfo() {
        HashMap<String, Object> params = new HashMap<>();
        params.put(BaseProtocolKey.ACCOUNT, SecureManager.getInstance().des(AccountUtils.getAccountName(_mActivity), 1, null));
        params.put(BaseProtocolKey.CHANNEL, ClientEngine.getInstance().CHANNEL);
        qualificationPresenterImpl.queryIDCardSupplimentInfo(params, true);
    }

    private void submitIDCardInfo() {
        String message = "";
        String frontUri = c_id_front_photo.getPicUri();
        String backUri = c_id_back_photo.getPicUri();
        String inHandUri = c_person_with_id.getPicUri();
        if (TextUtils.isEmpty(frontUri) || !c_id_front_photo.isLoadSuccess) {
            message = getString(R.string.tv_please_takephoto_front);
        } else if (TextUtils.isEmpty(backUri) || !c_id_back_photo.isLoadSuccess) {
            message = getString(R.string.tv_please_takephoto_back);
        } else if (TextUtils.isEmpty(inHandUri) || !c_person_with_id.isLoadSuccess) {
            message = getString(R.string.tv_please_takephoto_hold);
        }
        if (!TextUtils.isEmpty(message)) {
            DialogUtils.showToast(_mActivity, message);
            return;
        }
        doUpload();
    }


    private void refreshView() {
        HPLog.i(HPLog.LFP_TAG,"IDCardSupplementFragment::refreshView:cardStatus="+cardStatus.toString());
        if (cardStatus != null) {
            if (!TextUtils.isEmpty(cardStatus.getStatus())) {
                if (cardStatus.getStatus().equals(IDCardStatus.STATIC_STATUC_WAITE)) {//等待上传  提示信息都不显示
                    reupload_warning.setVisibility(View.GONE);
                    linear_tip_detail.setVisibility(View.VISIBLE);
                } else {
                    reupload_warning.setVisibility(View.VISIBLE);
                    if (cardStatus.getStatus().equals(IDCardStatus.STATIC_STATUC_FAIL)) {//审核失败显示红色提示信息
                        reupload_warning.setBackgroundResource(R.drawable.warring_msg_bg);
                        img_uploadcard_stuts.setBackgroundResource(R.drawable.error_exclamatory_mark);
                        tv_failDes0.setVisibility(View.VISIBLE);
                        tv_failDes.setText(getString(R.string.checkfailreason1) + cardStatus.getAuditInfo());
                    } else if (cardStatus.getStatus().equals(IDCardStatus.STATIC_STATUC_SUCCESS)) {//审核成功
                        reupload_warning.setBackgroundResource(R.drawable.shape_background_green);
                        img_uploadcard_stuts.setBackgroundResource(R.drawable.success);
                        tv_failDes.setTextColor(Color.rgb(27, 247, 46));
                        tv_failDes.setText(getString(R.string.idcard_verification_success));
                        linear_tip_detail.setVisibility(View.GONE);
                        btn_upload_cardpic.setVisibility(View.GONE);
                    } else {//审核中--框框样式改变  左边icon隐藏urce(R.drawable.input_msg_ing_bg);
                        img_uploadcard_stuts.setVisibility(View.GONE);
                        tv_failDes.setTextColor(Color.rgb(252, 190, 67));
                        tv_failDes.setText(getString(R.string.idcard_verification_ing));
                        btn_upload_cardpic.setVisibility(View.GONE);
                    }
                }
            }
            //"http://10.48.171.115:8080/hpayAcolyte-webapp/service/ShowEncryptoImage?pkValue=HXZZT@fplei05_patch_0&absolutelyFilePath=/mnt/mfs/static/hpay/risk/image/patch/HXZZT/20160825/fplei05_0_20160825151353=02=01.jpeg"
            //设置姓名，身份证值
            tv_tip_of_card_name.setText(cardStatus.getName());
            tv_tip_of_card_number.setText(CommonUtils.formattingCertNo4_2(cardStatus.getCertNo()));

            //这里传一个总的审核状态  没有 默认值为 01 待补件
            c_id_front_photo.initData(R.drawable.qualification_cardfront_hint,
                    cardStatus.getFrontCCPic(),
                    cardStatus.getFrontCCPicStatus(),
                    mUploadClickListener);
            c_id_back_photo.initData(R.drawable.qualification_back_hint,
                    cardStatus.getBackCCPic(),
                    cardStatus.getBackCCPicStatus(),
                    mUploadClickListener);
            c_person_with_id.initData(R.drawable.qualification_holdandcard_hint,
                    cardStatus.getHoldPic(),
                    cardStatus.getHoldPicStatus(),
                    mUploadClickListener);
        }
    }

    private void doUpload() {
        cancelTask();
        mTask = new MyAsyncTask<Void, BaseProtocolKey.TYPE, Integer>() {
            @Override
            protected void onPreExecute() {
                HPLog.i(HPLog.LFP_TAG, "IDCardSupplementFragment::MyAsyncTask:onPreExecute");
                progressDialog = new ProgressDialog(_mActivity);
                progressDialog.setMessage(getString(R.string.uploading_template, ""));//
                progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
                progressDialog.setCancelable(false);
                progressDialog.show();
                super.onPreExecute();
            }

            @Override
            protected void onPostExecute(Integer result) {
                HPLog.i(HPLog.LFP_TAG, "IDCardSupplementFragment::MyAsyncTask:onPostExecute");
                if (null != progressDialog) {
                    progressDialog.dismiss();
                    progressDialog = null;
                }
                if (CommonHelper.UPLOAD_SUCCESS == result) {//成功以后，删除图片
                    CommonUtils.removePics();
                    gotoUploadSuccess();
                } else if (CommonHelper.UPLOAD_FAIL == result) {////上传失败
                    DialogUtils.showToast(_mActivity, getString(R.string.upload_failed));
                } else if (CommonHelper.UPLOAD_CANCEL == result) {//上传取消
                    DialogUtils.showToast(_mActivity, getString(R.string.upload_cancel));
                }
                super.onPostExecute(result);
            }

            @Override
            protected void onProgressUpdate(BaseProtocolKey.TYPE... values) {
                HPLog.i(HPLog.LFP_TAG, "IDCardSupplementFragment::MyAsyncTask:onProgressUpdate.values="+values.toString());
                if (null != progressDialog) {
                    String picDes=CommonHelper.getPicDesWithPicType(_mActivity,values[0]);
                    progressDialog.setMessage(getString(R.string.uploading_template, picDes));
                }
                super.onProgressUpdate(values);
            }

            @Override
            protected void onCancelled(Integer result) {
                HPLog.i(HPLog.LFP_TAG, "IDCardSupplementFragment::MyAsyncTask:onCancelled");
                if (null != progressDialog) {
                    progressDialog.dismiss();
                    progressDialog = null;
                }
                //上传取消
                DialogUtils.showToast(_mActivity, getString(R.string.upload_cancel));
                super.onCancelled();
            }

            @Override
            protected Integer doInBackground(Void... params) {
                //发送正面图片
                if (!mFrontUploaded) {
                    if (startUpload(c_id_front_photo.getPicUri(), BaseProtocolKey.TYPE.FRONT)) {
                        this.publishProgress(BaseProtocolKey.TYPE.FRONT);
                        mFrontUploaded = true;
                    } else {
                        return CommonHelper.UPLOAD_FAIL;
                    }
                }
                if (this.isCancelled()) {
                    return CommonHelper.UPLOAD_CANCEL;
                }
                //发送反面图片
                if (!mBackUploaded) {
                    if (startUpload(c_id_back_photo.getPicUri(), BaseProtocolKey.TYPE.BACK)) {
                        this.publishProgress(BaseProtocolKey.TYPE.BACK);
                        mBackUploaded = true;
                    } else {
                        return CommonHelper.UPLOAD_FAIL;
                    }
                }
                if (this.isCancelled()) {
                    return CommonHelper.UPLOAD_CANCEL;
                }
                //发送手持图片
                if (!mInHandUploaded) {
                    if (startUpload(c_person_with_id.getPicUri(), BaseProtocolKey.TYPE.INHAND)) {
                        this.publishProgress(BaseProtocolKey.TYPE.INHAND);
                        mInHandUploaded = true;
                    } else {
                        return CommonHelper.UPLOAD_FAIL;
                    }
                }
                if (this.isCancelled()) {
                    return CommonHelper.UPLOAD_CANCEL;
                }
                return CommonHelper.UPLOAD_SUCCESS;
            }
        };
        mTask.execute();
    }

    /**
     * 开始上传图
     *
     * @param uri
     * @param type
     * @return
     */
    private boolean startUpload(String uri, BaseProtocolKey.TYPE type) {

        return CommonHelper.uploadPhotoJson(_mActivity, qualificationPresenterImpl, uri, type, CommonHelper.UploadModel.IDCARDSUPPLEMENT_UPLOADPICTURE);
    }

    //上传成功退出界面（等待3秒）
    private void gotoUploadSuccess() {
        DialogUtils.showToast(_mActivity, _mActivity.getString(R.string.upload_img_success));
        AccountUtils.setCertNoExporyStatus(_mActivity,AccountUtils.Account.CERTNO_CHECKING);
        //隐藏上传按钮reupload_warning
        btn_upload_cardpic.setEnabled(false);
        reupload_warning.setVisibility(View.GONE);
        btn_upload_cardpic.postDelayed(new Runnable() {
            @Override
            public void run() {
                pop();
            }
        }, 3000);
    }

    @Override
    public void submitIDCardSupplementSuccess(IDCardStatus idCardStatus) {
        HPLog.i(HPLog.LFP_TAG, "IDCardSupplementFragment::submitIDCardSupplementSuccess::idCardStatus=" + idCardStatus.toString());
        root_scroll.setVisibility(View.VISIBLE);
        cardStatus = idCardStatus;
        refreshView();
    }

    @Override
    public void submitIDCardSupplementFail(String errorMsg) {
        HPLog.i(HPLog.LFP_TAG, "IDCardSupplementFragment::submitIDCardSupplementFail::errorMsg=" + errorMsg);

    }

    private void cancelTask() {
        //当该activity不可见的时候，取消上传任务。
        if (null != mTask) {
            HPLog.i("ssss", "cancel task");
            mTask.cancel(true);
            mTask = null;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (Activity.RESULT_OK == resultCode) {
            QualificationPhotoView photo = null;
            if (TAKE_PICTURE_FRONT == requestCode) {
                photo = c_id_front_photo;
            } else if (TAKE_PICTURE_BLACK == requestCode) {
                photo = c_id_back_photo;
            } else if (TAKE_PICTURE_IN_HAND == requestCode) {
                photo = c_person_with_id;
            }
            if (mPicUri != null) {
                String uri = mPicUri.toString();
                photo.setPic(uri);
            }
        }
        mPicUri = null;
    }

    @Override
    public void permissionYes(List<String> permissions) {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        mPicUri = CommonUtils.randomUri(CommonUtils.getAccessDir());
        HPLog.i(HPLog.LFP_TAG, "onUploadClickListener-mPicUri:" + mPicUri.toString());
        intent.putExtra(MediaStore.EXTRA_OUTPUT, mPicUri);
        intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        startActivityForResult(intent, CurrentRequestCode);
    }

    @Override
    public void permissionFail(List<String> permissions) {
        // 用户否勾选了不再提示并且拒绝了权限，那么提示用户到设置中授权。
        if (AndPermission.hasAlwaysDeniedPermission(_mActivity, permissions)) {
            // 第一种：用默认的提示语。
            AndPermission.defaultSettingDialog(IDCardSupplementFragment.this, PermissionCode.REQUEST_CODE_SETTING).show();
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        hideSoftInput();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        cancelTask();
        qualificationPresenterImpl.onDestory();
    }
}
